from flask import Flask, render_template, request, redirect, url_for, session
from datetime import datetime, timedelta

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于session管理

# 模拟的用户数据，包括班级信息
users = {
    'teacher': [],
    'student': [],
    'parent': []
}

# 模拟的班级数据
classes = {}

# 模拟考试数据
exams = {}


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if 'login' in request.form:
            user_type = request.form['user_type']
            username = request.form['username']
            password = request.form['password']

            for user in users[user_type]:
                if user['username'] == username and user['password'] == password:
                    session['username'] = username
                    session['user_type'] = user_type
                    return redirect(url_for(f'{user_type}_dashboard', username=username))
            return "登录失败，用户名或密码错误！"

    return render_template('login.html')


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        machine_id = request.form['machine_id']
        password = request.form['password']

        # 检查用户名是否已存在
        for user_type_key in users:
            for user in users[user_type_key]:
                if user['username'] == username:
                    return "用户名已存在，请选择其他用户名。"

        # 添加新用户，包含用户的用户名、机号和密码
        users[user_type].append({'username': username, 'machine_id': machine_id, 'password': password, 'class': None})
        return redirect(url_for('register_success'))

    return render_template('register.html')


@app.route('/register_success')
def register_success():
    return render_template('register_success.html')


@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        new_password = request.form['new_password']

        for user in users[user_type]:
            if user['username'] == username:
                user['password'] = new_password
                return redirect(url_for('password_reset_success'))

        return "用户名不存在。"

    return render_template('forgot_password.html')


@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')


# 学生页面
@app.route('/student_dashboard/<username>', methods=['GET', 'POST'])
def student_dashboard(username):
    if request.method == 'POST':
        class_name = request.form['class_name']
        for student in users['student']:
            if student['username'] == username:
                student['class'] = class_name
                if class_name not in classes:
                    classes[class_name] = []
                classes[class_name].append(username)
                return f"成功加入班级 {class_name}!"

    # 检查是否有正在进行的考试
    exam = session.get('exam')
    if exam:
        remaining_time = exam['end_time'] - datetime.now()
        if remaining_time.total_seconds() <= 0:
            return "考试时间已到，系统已自动提交。"
        return render_template('exam.html', remaining_time=remaining_time.total_seconds())

    return render_template('student_dashboard.html', username=username)


# 老师页面
@app.route('/teacher_dashboard/<username>', methods=['GET', 'POST'])
def teacher_dashboard(username):
    if request.method == 'POST':
        class_name = request.form.get('class_name', '')
        if not class_name:
            return "班级名称不能为空", 400  # Bad request
        # 处理班级管理逻辑
        return redirect(url_for('class_management', class_name=class_name))

    return render_template('teacher_dashboard.html', username=username)


@app.route('/manage_class/<username>', methods=['GET', 'POST'])
def manage_class(username):
    if request.method == 'POST':
        class_name = request.form.get('class_name', '')
        if not class_name:
            return "班级名称不能为空", 400  # Bad request
        # 处理班级管理逻辑
        return redirect(url_for('class_management', class_name=class_name))

    return render_template('teacher_dashboard.html', username=username)


@app.route('/class_management/<class_name>', methods=['GET'])
def class_management(class_name):
    students = classes.get(class_name, [])
    # 这里可能需要根据实际情况检查是否有正在进行的考试
    exam_active = False
    if class_name in exams:
        exam_active = datetime.now() < exams[class_name]['end_time']
    return render_template('class_management.html', class_name=class_name, students=students, exam_active=exam_active)


@app.route('/exam_management/<username>', methods=['GET', 'POST'])
def exam_management(username):
    if request.method == 'POST':
        class_name = request.form.get('class_name', '')
        exam_duration = request.form.get('exam_duration', '')
        if not class_name or not exam_duration:
            return "班级名称和考试时长不能为空", 400  # Bad request

        # 设置考试时间的逻辑
        end_time = datetime.now() + timedelta(minutes=int(exam_duration))
        exams[class_name] = {
            'start_time': datetime.now(),
            'end_time': end_time
        }
        session['exam'] = exams[class_name]

        # 设置考试时间后重定向到班级管理页面或其他页面
        return redirect(url_for('class_management', class_name=class_name))

    return render_template('exam_management.html', username=username)


@app.route('/set_exam_time/<username>', methods=['GET', 'POST'])
def set_exam_time(username):
    if request.method == 'POST':
        class_name = request.form.get('class_name', '')
        exam_duration = request.form.get('exam_duration', '')
        if not class_name or not exam_duration:
            return "班级名称和考试时长不能为空", 400  # Bad request

        # 设置考试时间的逻辑
        end_time = datetime.now() + timedelta(minutes=int(exam_duration))
        exams[class_name] = {
            'start_time': datetime.now(),
            'end_time': end_time
        }
        session['exam'] = exams[class_name]
        return f"考试时间已设置为 {exam_duration} 分钟"

    return render_template('set_exam_time.html', username=username)


# 家长页面
@app.route('/parent_dashboard/<username>')
def parent_dashboard(username):
    return render_template('parent_dashboard.html', username=username)


if __name__ == '__main__':
    app.run(debug=True)
